package ru.vms.healthcontrol;

import java.util.Date;
import java.util.List;

import pro.notum.interfaces.Command;
import pro.notum.interfaces.IModel;
import pro.notum.interfaces.IPresenter;
import pro.notum.interfaces.IView;
import pro.notum.mobile.R;
import android.app.Activity;
import android.app.TabActivity;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;



public class MainActivity extends Activity implements IPresenter {

	public static final String GRAPH_TAB = "graph";
	public static final String SETTINGS_TAB = "settings";
	public static final String HOME_TAB = "home";
	
	IView view = null;
	IModel model = null;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_container);
        
        String packageName = getApplicationContext().getPackageName();
        // Setup Version information label
        PackageInfo pinfo;
		try {
			pinfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
	        String sTitle = this.getTitle().toString();
	        this.setTitle(String.format("%s v%s",sTitle,pinfo.versionName));
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		} 
        
        
        // Init tabs
        TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        
        TabHost.TabSpec tabSpec;
        
        View v = getLayoutInflater().inflate(R.layout.header_template, null);
        ImageView iv = (ImageView) v.findViewById(R.id.header_image);
        iv.setImageResource(R.drawable.home_tab_selector);
        
        tabSpec = tabHost.newTabSpec(HOME_TAB);
        tabSpec.setIndicator(v);
        tabSpec.setContent(R.id.home_tab);
        tabHost.addTab(tabSpec);
        
        View v2 = getLayoutInflater().inflate(R.layout.header_template, null);
        ImageView iv2 = (ImageView) v2.findViewById(R.id.header_image);
        iv2.setImageResource(R.drawable.home_tab_selector);
        
        tabSpec = tabHost.newTabSpec(SETTINGS_TAB);
        tabSpec.setIndicator(v2);
        tabSpec.setContent(R.id.settings_tab);
        tabHost.addTab(tabSpec);

        View v3 = getLayoutInflater().inflate(R.layout.header_template, null);
        ImageView iv3 = (ImageView) v3.findViewById(R.id.header_image);
        iv3.setImageResource(R.drawable.home_tab_selector);
        
        tabSpec = tabHost.newTabSpec(GRAPH_TAB);
        tabSpec.setIndicator(v3);
        tabSpec.setContent(R.id.graph_tab);
        tabHost.addTab(tabSpec);
        
        tabHost.setOnTabChangedListener( new OnTabChangeListener() {
			
			public void onTabChanged(String tabId) {
				view.selectTab(tabId);
			}
		});

        model = new NotumModel(this);
        view = new NotumView(this);
    }

    protected void onResume () {
    	
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    	String sex = sp.getString("sex", "???");
    	String age = sp.getString("age", "???");
    	String height = sp.getString("height", "???");
        String text = "sex: " + sex + " age:"+ age + " height:"+height; 
        Log.v("sinner",text);
        
        
        model.userPreferencesChanged();
        view.updateUserInfo();
        super.onResume();
    }

	public Activity getActivity() {
		return this;
	}


	public UserData getUserData() {
		return model.getUserData();
	}


	public ValueUnderControl loadValuesForControl(Date date) {

		// request to DB by date 
		
		ValueUnderControl v = ValueUnderControl.create(ValueUnderControl.WEIGHT, this);
		v.set(55.5f, 10, 80, date);
		
		return v;
	}

	public void saveBtnPressed() {
		
		Date d = view.getDate();
		ValueUnderControl value = view.getModifiedValues();
		
		if( model.isExistValuesForDate(d) ) {
			view.AskUserToUpdate( new DBUpdateCommand(this) );
		} else {
			model.insert(value);
			NetLog.Toast(getApplicationContext(), getString(R.string.save_complete));
		}
		
		model.selectAllLog();
	}
	
	class DBUpdateCommand implements Command {

		IPresenter p = null;
		
		public DBUpdateCommand (IPresenter p ) {
			this.p = p;
		}
		
		public void doCommand() {
			p.updateValuesInDB();
			NetLog.Toast(p.getActivity().getApplicationContext(), getString(R.string.save_complete));
		}
		
	}

	public void updateValuesInDB() {
		// TODO get value from view and update value IN DB
		NetLog.v("updateValuesInDB");
		
		ValueUnderControl value = view.getModifiedValues();
		model.update(value);
		
	}

	public void signInOut() {

		UserData user = model.getUserData();
		
		if( user.isLoginComplete ) {
			model.signOutNotumPro();
			view.updateUserInfo();
			NetLog.Toast(getApplicationContext(), getString(R.string.logout_notum));
			
		} else if ( user.isReadyToSignIn() ) {
			
			if ( model.signInNotumPro() )
				view.beginWaitDialog(getString(R.string.wait_authorization));
			
		} else {
			view.AskUserToChangeSettings(getString(R.string.invalid_account_data));
		}
		
	}

	public void requestComplete() {
		
		RequestResult r = model.getLastRequestResult();
		
		NetLog.i("requestCompete  type = %s , result = %d, success: %b", r.getType().toString(), r.getResult(),r.isSucceess());
		
		view.stopWaitDialog();
		
		if ( r.getResult() >= 0 && r.isSucceess() ) {
			processSuccessRequest(r);
			
		} else {
			processFailedRequest(r);
		}
		
		
	}

	private void processFailedRequest(RequestResult r) {
		RequestResult.ReqType type = r.getType();
		
		if( type == RequestResult.ReqType.AUTHORIZATION ) {
			view.AskUserToChangeSettings(r.getErrortext());
			
		} else if ( type == RequestResult.ReqType.UNDEFINED ) {
			view.printError(r.getErrortext());
			
		} else if ( type == RequestResult.ReqType.SEND_WEIGHT ){
			NetLog.i("Send weight complete");
		}
		
	}

	private void processSuccessRequest(RequestResult r) {
		RequestResult.ReqType type = r.getType();
		
		if( type == RequestResult.ReqType.AUTHORIZATION ) {
			view.updateUserInfo();
			NetLog.Toast(this, "%s", getString(R.string.auth_succes));
			
		} else if ( type == RequestResult.ReqType.UNDEFINED ) {
			NetLog.Toast(this, "ooops undefined error");
			
		} else if ( type == RequestResult.ReqType.SEND_WEIGHT ){
			NetLog.i("Send weight complete");
		}
		
		
	}

	public boolean isExistValuesForDate(Date d) {
		return model.isExistValuesForDate(d);
	}

	public List<ValueUnderControl> selectByName(String name) {
		return model.selectByName(name);
	};
	
	
}


